package org.apache.dubbo.rpc.model;

import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ServiceConfigBase;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * ProviderModel is about published services
 */
public class ProviderModel {

    private String serviceKey;
    private final Object serviceInstance;
    private final ServiceDescriptor serviceModel;
    private final ServiceConfigBase<?> serviceConfig;
    private final List<RegisterStatedURL> urls;

    public ProviderModel(String serviceKey,Object serviceInstance,ServiceDescriptor serviceModel,
                         ServiceConfigBase<?> serviceConfig) {
        if (serviceInstance == null) {
            throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL.");
        }

        this.serviceKey = serviceKey;
        this.serviceInstance = serviceInstance;
        this.serviceModel = serviceModel;
        this.serviceConfig = serviceConfig;
        this.urls = new ArrayList<>(1);
    }

    public String getServiceKey() {
        return serviceKey;
    }


    public Class<?> getServiceInterfaceClass() {
        return serviceModel.getServiceInterfaceClass();
    }

    public Object getServiceInstance() {
        return serviceInstance;
    }

    public Set<MethodDescriptor> getAllMethods() {
        return serviceModel.getAllMethods();
    }

    public ServiceDescriptor getServiceModel() {
        return serviceModel;
    }

    public ServiceConfigBase<?> getServiceConfig() {
        return serviceConfig;
    }

    public List<RegisterStatedURL> getStatedUrl() {
        return urls;
    }

    public void addStatedUrl(RegisterStatedURL url) {
        this.urls.add(url);
    }

    public static class RegisterStatedURL {
        private volatile URL registryUrl;
        private volatile URL providerUrl;
        private volatile boolean registered;

        public RegisterStatedURL(URL providerUrl,URL registryUrl,boolean registered) {
            this.providerUrl = providerUrl;
            this.registryUrl = registryUrl;
            this.registered = registered;
        }

        public URL getProviderUrl() {
            return providerUrl;
        }

        public void setProviderUrl(URL providerUrl) {
            this.providerUrl = providerUrl;
        }

        public boolean isRegistered() {
            return registered;
        }

        public void setRegistered(boolean registered) {
            this.registered = registered;
        }

        public URL getRegistryUrl() {
            return registryUrl;
        }

        public void setRegistryUrl(URL registryUrl) {
            this.registryUrl = registryUrl;
        }
    }

    /* *************** Start, metadata compatible **************** */

    private ServiceMetadata serviceMetadata;
    private final Map<String,List<MethodDescriptor>> methods = new HashMap<>();

    public ProviderModel(String serviceKey,Object serviceInstance,ServiceDescriptor serviceModel,
                         ServiceConfigBase<?> serviceConfig,ServiceMetadata serviceMetadata) {
        this(serviceKey,serviceInstance,serviceModel,serviceConfig);
        this.serviceMetadata = serviceMetadata;
        initMethod(serviceModel.getServiceInterfaceClass());
    }

    public void setServiceKey(String serviceKey) {
        this.serviceKey = serviceKey;
        if (serviceMetadata != null) {
            serviceMetadata.setServiceKey(serviceKey);
            serviceMetadata.setGroup(BaseServiceMetadata.groupFromServiceKey(serviceKey));
        }
    }

    public String getServiceName() {
        return this.serviceMetadata.getServiceKey();
    }

    public List<MethodDescriptor> getAllMethodModels() {
        return methods.values()
                .stream()
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
    }

    public MethodDescriptor getMethodModel(String methodName,String[] argTypes) {
        List<MethodDescriptor> methodModels = methods.get(methodName);
        if (methodModels != null) {
            return methodModels.stream()
                    .filter(m -> Arrays.equals(argTypes,m.getCompatibleParamSignatures()))
                    .findFirst().orElse(null);
        }
        return null;
    }

    public List<MethodDescriptor> getMethodModelList(String methodName) {
        List<MethodDescriptor> results = methods.get(methodName);
        return results == null ? Collections.emptyList() : results;
    }

    private void initMethod(Class<?> serviceInterfaceClass) {
        Method[] methodsToExport = serviceInterfaceClass.getMethods();

        for (Method method : methodsToExport) {
            method.setAccessible(true);

            List<MethodDescriptor> methodModels = methods.computeIfAbsent(method.getName(), k -> new ArrayList<>());
            methodModels.add(new MethodDescriptor(method));
        }
    }

    /**
     * @return serviceMetadata
     */
    public ServiceMetadata getServiceMetadata() {
        return serviceMetadata;
    }
}
